import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Row, Col, Input, Select, Spin, AutoComplete } from 'antd';
import HOCSelect from '@/components/AntDesign/Select';
import Area from '../../../components/Area';

const FormItem = Form.Item;
const { Option } = Select;
const { Search } = Input;
@connect(({ loading }) => ({
  loading: loading.models.suppliermaintenance,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      custList: [],
    };
  }

  componentDidMount() {}

  // 地区
  getData = (value, id) => {
    const { form } = this.props;
    const tempAreaId = value.key;
    if (id) {
      form.setFieldsValue({ [id]: { key: tempAreaId } });
      this.setState({ [id]: tempAreaId });
    }
  };

  // 搜索供应商
  searchCust = value => {
    this.setState({ loading: true });
    const { form } = this.props;
    const { dispatch } = this.props;
    dispatch({
      type: 'suppliermaintenance/fetchNameList',
      payload: { name: value },
      callback: res => {
        this.setState({ loading: false });
        if (res.success && res.data) {
          this.setState({
            custList: res.data,
          });
          // const getFieldsList = form.getFieldsValue();
          // Object.keys(getFieldsList).forEach(key => {
          //   if(!res.data.length){
          //     form.setFieldsValue({ name: value, mdSuppId: null });
          //     form.setFieldsValue({ no: null });
          //   }
          //   if (key === 'corpNature' || key === 'industryCode') {
          //     form.setFieldsValue({ no: null });
          //     form.setFieldsValue({
          //       [key]: { key: `${res.data[key]}`, mdSuppId: null },
          //     });
          //     form.setFieldsValue({ no: null });
          //   } else if (key === 'areaId') {
          //     form.setFieldsValue({
          //       [key]: { key: res.data.areaId, label: res.data.areaName },
          //     });
          //   } else {
          //     form.setFieldsValue({ [key]: res.data[key], mdSuppId: null });
          //     form.setFieldsValue({ no: null });
          //   }
          // });
        } else {
          console.log("object")
          this.setState({ custList: [] });
        }
      },
    });
  };

  searchCusttwo = value => {
    this.setState({ loading: true });
    const { dispatch, form, getCustName = () => {}, getCustNametwo = () => {} } = this.props;
    dispatch({
      type: 'suppliermaintenance/fetchSuppList',
      payload: { uniCreditCode: value },
      callback: res => {
        // if (!JSON.stringify(res.data) ==="{}" && (!res.data.areaId || !res.data.mdSuppId)) {
        //   form.resetFields(['name', 'areaId']);
        // }
         // 包裹后 
        // console.log(form.getFieldsValue("name"),'res.data')
       
         const getFieldsList = form.getFieldsValue();

        getCustName(res.data.name ||getFieldsList.name );
        getCustNametwo(res.data.uniCreditCode);
        this.setState({ loading: false });
        if (res.success) {
          Object.keys(getFieldsList).forEach(key => {
            if (res.data[key]) {
              if (key === 'corpNature' || key === 'industryCode') {
                form.setFieldsValue({
                  [key]: { key: `${res.data[key]}`, mdSuppId: null },
                });
                form.setFieldsValue({ no: null });
              } else if (key === 'areaId') {
                form.setFieldsValue({
                  [key]: { key: res.data.areaId, label: res.data.areaName },
                });
              } else {
                form.setFieldsValue({ [key]: res.data[key], mdSuppId: null });
                form.setFieldsValue({ no: null });
              }
            }
          });
        } else {
          this.setState({ loading: false });
        }
      },
    });
  };

  // 选择某一供应商
  selectCust = custId => {
    const { custList } = this.state;
    const { getCustName = () => {}, getCustNametwo = () => {}, form } = this.props;
    let custInfo = null;
    custList.forEach(item => {
      if (custId === item.mdSuppId) {
        custInfo = item;
      }
    });

    getCustName(custInfo.name);
    getCustNametwo(custInfo.uniCreditCode);
    const getFieldsList = form.getFieldsValue();
    Object.keys(getFieldsList).forEach(key => {
      if (custInfo[key]) {
        if (key === 'corpNature' || key === 'industryCode') {
          form.setFieldsValue({ [key]: { key: `${custInfo[key]}`, mdSuppId: null } });
          form.setFieldsValue({ no: null });
        } else if (key === 'areaId') {
          form.setFieldsValue({
            [key]: { key: custInfo.areaId, label: custInfo.areaName },
          });
        } else {
          form.setFieldsValue({ [key]: custInfo[key], mdSuppId: null });
          form.setFieldsValue({ no: null });
        }
      }
    });
  };

  slelce = e => {
    const { custList } = this.state;
    const { getCustName, getCustNametwo } = this.props;
    let names = '';
    custList.forEach(item => {
      if (e === item.mdSuppId) {
        getCustName(item.name);
        getCustNametwo(item.uniCreditCode);
        names = 1;
      }
    });
    if (names !== 1) {
      getCustName(e);
    }
  };

  slelcetwo = e => {
    const { getCustNametwo } = this.props;
    getCustNametwo(e);
  };

  render() {
    const { loading, custList } = this.state;
    const {
      form: { getFieldDecorator },
      suppTypeList,
      isHasSuppType,
    } = this.props;
    // 表单布局
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };

    // 供应商类型
    const suppTypeOL = suppTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    const options = custList.map(opt => (
      <Option key={opt.mdSuppId} value={opt.mdSuppId}>
        {opt.name}
      </Option>
    ));
    return (
      <Card
        title={<span style={{ fontWeight: 'bolder' }}>供应商基本信息</span>}
        bordered={false}
        style={{ marginBottom: 24 }}
      >
        <Spin tip="Loading..." spinning={loading}>
          <Form layout="vertical">
            <Row gutter={64}>
              <Col {...colProps} md={8} sm={24}>
                <FormItem label="供应商名称">
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <AutoComplete
                      dataSource={options}
                      onSelect={this.selectCust}
                      onChange={this.slelce}
                    >
                      <Search
                        placeholder="请输入关键字检索"
                        maxLength={100}
                        onSearch={value => this.searchCust(value)}
                      />
                    </AutoComplete>
                  )}
                </FormItem>
              </Col>
              {isHasSuppType ? (
                <Col {...colProps}>
                  <FormItem label="供应商类型">
                    {getFieldDecorator('type', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        labelInValue
                        optionFilterProp="children"
                      >
                        {suppTypeOL}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              ) : null}
              <Col {...colProps}>
                <FormItem label="地区">
                  {getFieldDecorator('areaId', {
                    rules: [{ required: true, message: '请选择' }],
                  })(<Area onChange={value => this.getData(value, 'areaId')} labelInValue />)}
                </FormItem>
              </Col>
              {isHasSuppType ? <div style={{ clear: 'both' }} /> : null}
              <Col {...colProps}>
                <FormItem label="统一社会信用代码">
                  {getFieldDecorator('uniCreditCode', {
                    rules: [
                      {
                        required: true,
                        message: '18位的数字与字母组合',
                        pattern: /^[A-Za-z0-9]{18}$/,
                      },
                    ],
                  })(
                    <AutoComplete onChange={this.slelcetwo}>
                      <Search
                        placeholder="请输入关键字检索"
                        maxLength={100}
                        onSearch={value => this.searchCusttwo(value)}
                      />
                    </AutoComplete>
                  )}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="办公地址">
                  {getFieldDecorator('officeAddr', {
                    rules: [{ required: false, message: '请输入' }],
                  })(<Input placeholder="请输入" maxLength="100" />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="工作邮箱">
                  {getFieldDecorator('email', {
                    rules: [{ required: false, type: 'email', message: '应为邮箱格式' }],
                  })(<Input placeholder="请输入" maxLength="50" />)}
                </FormItem>
              </Col>
              {isHasSuppType ? <div style={{ clear: 'both' }} /> : null}
              <Col {...colProps}>
                <FormItem label="联系电话">
                  {getFieldDecorator('tel', {
                    rules: [
                      {
                        required: false,
                        message: '固话或手机',
                        pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                      },
                    ],
                  })(<Input placeholder="请输入" maxLength="12" />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {})(<Input placeholder="请输入" maxLength="200" />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Spin>
      </Card>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
